# role_permission_dao.py
from sqlalchemy.orm import Session, joinedload
from ..do.role_permission_do import RolePermissionModel


def getRolePermission(db: Session, role_id: str, permission_id: str):
    return db.query(RolePermissionModel).filter(RolePermissionModel.role_id == role_id, RolePermissionModel.permission_id == permission_id).first()


def getRolePermissions(db: Session, skip: int = 0, limit: int = 100):
    return db.query(RolePermissionModel).offset(skip).limit(limit).all()


def createRolePermission(db: Session, role_permission):
    rolePermissionModel = RolePermissionModel(**role_permission)
    db.add(rolePermissionModel)
    db.commit()
    db.refresh(rolePermissionModel)
    return rolePermissionModel


def deleteRolePermission(db: Session, role_id: str, permission_id: str):
    rolePermissionModel = getRolePermission(db, role_id, permission_id)
    if rolePermissionModel is None:
        return False
    db.delete(rolePermissionModel)
    db.commit()
    return True

def get_permissions_by_role_id(db: Session, role_id: str):
     rtn=db.query(RolePermissionModel).options(joinedload(RolePermissionModel.permission)).filter(RolePermissionModel.role_id == role_id).all()
     return rtn

def delete_role_permissions_by_role_id(db: Session, role_id: str):
    db.query(RolePermissionModel).filter(RolePermissionModel.role_id == role_id).delete()
    db.commit()
    return True

def get_permissions_by_permission_id(db: Session, permission_id: str):
    rtn=db.query(RolePermissionModel).options(joinedload(RolePermissionModel.role)).filter(RolePermissionModel.permission_id == permission_id).all()
    return rtn
